package com.logicalthinking.socialmall.biz;

import com.github.chenlijia1111.commonModule.utils.SpringUtil;
import com.github.chenlijia1111.utils.common.Result;
import com.github.chenlijia1111.utils.common.constant.BooleanConstant;
import com.github.chenlijia1111.utils.core.JSONUtil;
import com.github.chenlijia1111.utils.core.StringUtils;
import com.github.chenlijia1111.utils.database.mybatis.pojo.PageInfo;
import com.github.chenlijia1111.utils.encrypt.AESUtil;
import com.github.chenlijia1111.utils.encrypt.MD5EncryptUtil;
import com.github.chenlijia1111.utils.list.Lists;
import com.github.chenlijia1111.utils.oauth.jwt.JWTUtil;
import com.github.chenlijia1111.utils.oauth.wx.WXAppletsLoginUtil;
import com.github.chenlijia1111.utils.oauth.wx.WXCommonLoginUtil;
import com.logicalthinking.socialmall.common.enums.UserSourceEnum;
import com.logicalthinking.socialmall.common.pojo.Constants;
import com.logicalthinking.socialmall.common.vo.requestVo.clientUser.*;
import com.logicalthinking.socialmall.common.vo.responseVo.clientUser.ClientUserListVo;
import com.logicalthinking.socialmall.common.vo.responseVo.clientUser.ClientUserSimpleInfoVo;
import com.logicalthinking.socialmall.common.vo.responseVo.clientUser.ShopApplyUserListVo;
import com.logicalthinking.socialmall.entity.*;
import com.logicalthinking.socialmall.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 客户端用户
 *
 * @author chenLiJia
 * @since 2020-02-17 14:43:59
 **/
@Service
public class ClientUserBiz {


    @Autowired
    private ClientUserServiceI clientUserService;//用户
    @Autowired
    private ThirdPartyUsersServiceI thirdPartyUsersService;//第三方用户
    @Autowired
    private ClientAuthenticateSelfServiceI clientAuthenticateSelfService;//个人认证注册
    @Autowired
    private ClientAuthenticateShopServiceI clientAuthenticateShopService;//商家认证注册
    @Autowired
    private ClientUserLoginHistoryServiceI clientUserLoginHistoryService;//用户登陆记录

    //微信工具
    private WXCommonLoginUtil wxCommonLoginUtil = new WXCommonLoginUtil();


    /**
     * 添加未认证用户
     *
     * @param params
     * @return
     */
    public Result addNotAuthenticateUser(AdminAddClientUserParams params) {
        //判断手机号是否已存在
        List<ClientUser> clientUsers = clientUserService.listByCondition(new ClientUser().
                setTelephone(params.getTelephone()).setDeleteStatus(BooleanConstant.NO_INTEGER));
        if (Lists.isNotEmpty(clientUsers)) {
            return Result.failure("手机号码已被使用");
        }

        ClientUser clientUser = new ClientUser().setName(params.getNickName()).
                setTelephone(params.getTelephone()).setSex(params.getSex()).
                setUserType(1).setCreateTime(new Date()).
                setUpdateTime(new Date()).setDeleteStatus(BooleanConstant.NO_INTEGER).
                setOpenStatus(BooleanConstant.YES_INTEGER);
        if (StringUtils.isNotEmpty(params.getPassword())) {
            String password = MD5EncryptUtil.MD5StringToHexString(params.getPassword() + Constants.PASSWORD_SALT);
            clientUser.setPassword(password);
        }
        return clientUserService.add(clientUser);
    }

    /**
     * 添加个人认证用户
     *
     * @param params
     * @return
     */
    public Result addAuthenticateSelfUser(AdminAddClientUserParams params) {
        //判断手机号是否已存在
        List<ClientUser> clientUsers = clientUserService.listByCondition(new ClientUser().
                setTelephone(params.getTelephone()).setDeleteStatus(BooleanConstant.NO_INTEGER));
        if (Lists.isNotEmpty(clientUsers)) {
            return Result.failure("手机号码已被使用");
        }

        ClientUser clientUser = new ClientUser().setName(params.getNickName()).
                setTelephone(params.getTelephone()).setSex(params.getSex()).
                setUserType(2).setCreateTime(new Date()).
                setUpdateTime(new Date()).setDeleteStatus(BooleanConstant.NO_INTEGER).
                setOpenStatus(BooleanConstant.YES_INTEGER);
        if (StringUtils.isNotEmpty(params.getPassword())) {
            String password = MD5EncryptUtil.MD5StringToHexString(params.getPassword() + Constants.PASSWORD_SALT);
            clientUser.setPassword(password);
        }
        Result result = clientUserService.add(clientUser);
        if (result.getSuccess()) {
            //添加个人认证信息
            ClientAuthenticateSelf clientAuthenticateSelf = new ClientAuthenticateSelf();
            clientAuthenticateSelf.setUserId(clientUser.getId()).
                    setTelephone(params.getTelephone()).setName(params.getNickName()).
                    setCreateTime(new Date()).setUpdateTime(new Date());
            clientAuthenticateSelfService.add(clientAuthenticateSelf);

        }
        return result;
    }

    /**
     * 添加商家认证用户
     *
     * @param params
     * @return
     */
    public Result addAuthenticateSelfShop(AdminAddClientUserToShopParams params) {
        //判断手机号是否已存在
        List<ClientUser> clientUsers = clientUserService.listByCondition(new ClientUser().
                setTelephone(params.getTelephone()).setDeleteStatus(BooleanConstant.NO_INTEGER));
        if (Lists.isNotEmpty(clientUsers)) {
            return Result.failure("手机号码已被使用");
        }

        ClientUser clientUser = new ClientUser().setName(params.getName()).
                setTelephone(params.getTelephone()).setSex(0).
                setUserType(3).setCreateTime(new Date()).
                setUpdateTime(new Date()).setDeleteStatus(BooleanConstant.NO_INTEGER).
                setOpenStatus(BooleanConstant.YES_INTEGER);
        if (StringUtils.isNotEmpty(params.getPassword())) {
            String password = MD5EncryptUtil.MD5StringToHexString(params.getPassword() + Constants.PASSWORD_SALT);
            clientUser.setPassword(password);
        }
        Result result = clientUserService.add(clientUser);
        if (result.getSuccess()) {
            //添加商家认证信息
            ClientAuthenticateShop clientAuthenticateShop = new ClientAuthenticateShop();
            BeanUtils.copyProperties(params, clientAuthenticateShop);

            clientAuthenticateShop.setUserId(clientUser.getId());
            clientAuthenticateShop.setReviewStatus(Constants.REVIEW_STATUS_AGGRE);
            clientAuthenticateShopService.add(clientAuthenticateShop);
        }
        return result;
    }


    /**
     * 获取微信openId
     *
     * @param wechatCode
     * @return
     */
    public Result wechatLogin(String wechatCode) {
        //获取openId,access_key
        Map map = new WXAppletsLoginUtil().accessToken(Constants.WX_APP_ID, Constants.WX_APP_SECRET, wechatCode);

        //获取一下accessToken
        Map map1 = wxCommonLoginUtil.accessToken(Constants.WX_APP_ID, Constants.WX_APP_SECRET, wechatCode);
        Object access_token = map1.get("access_token");
        if (Objects.nonNull(access_token)) {
            map.put("access_token", access_token);
        }

        //判断用户是否已存在,如果已经存在,直接返回用户信息以及token
        //如果不存在,通过openId获取用户信息创建用户
        Object openid = map.get("openid");

        //用户信息
        ClientUser clientUser = null;

        if (Objects.nonNull(openid)) {
            String openId = (String) openid;
            ThirdPartyUsers thirdPartyUsersCondition = new ThirdPartyUsers().setOpenid(openId);
            List<ThirdPartyUsers> thirdPartyUsers = thirdPartyUsersService.listByCondition(thirdPartyUsersCondition);
            if (Lists.isNotEmpty(thirdPartyUsers)) {
                //已经存在了,获取用户信息
                ThirdPartyUsers thirdPartyUser = thirdPartyUsers.get(0);
                Integer clientUserId = thirdPartyUser.getClientUserId();
                clientUser = clientUserService.findById(clientUserId);

                if (Objects.nonNull(clientUser)) {
                    //返回token
                    //返回token
                    String jwtToken = JWTUtil.createJWT(String.valueOf(clientUser.getId()), clientUser.getName(), Constants.APP_LOGIN_LIMIT_TIME_SECONDS * 1000L, Constants.JWT_SIGN_KEY);
                    HttpServletResponse response = SpringUtil.getCurrentResponse();
                    response.setHeader(Constants.TOKEN, jwtToken);
                }
            } else {
                //不存在,是新用户
                //获取微信用户信息
                if (Objects.nonNull(access_token)) {
                    String accessToken = (String) access_token;
                    Map userInfo = new WXCommonLoginUtil().userInfo(accessToken, openId);
                    String nickname = (String) userInfo.get("nickname");
                    String sex = (String) userInfo.get("sex");
                    String province = (String) userInfo.get("province");
                    String city = (String) userInfo.get("city");
                    String country = (String) userInfo.get("country");
                    String headimgurl = (String) userInfo.get("headimgurl");


                    //构建信息
                    //插入用户信息
                    clientUser = new ClientUser().setName(nickname).
                            setPassword(MD5EncryptUtil.MD5StringToHexString(Constants.ADMIN_INIT_PASSWORD + Constants.PASSWORD_SALT)).
                            setSex(Integer.valueOf(sex)).
                            setUserType(1).
                            setCreateTime(new Date()).
                            setUpdateTime(new Date()).
                            setDeleteStatus(BooleanConstant.NO_INTEGER).
                            setOpenStatus(BooleanConstant.NO_INTEGER);
                    clientUserService.add(clientUser);


                    //第三方登陆信息
                    ThirdPartyUsers thirdPartyUser = new ThirdPartyUsers().setOpenid(openId).
                            setClientUserId(clientUser.getId()).
                            setUsername(nickname).
                            setNickname(nickname).
                            setAvatar(headimgurl).
                            setGender(sex).
                            setSource(UserSourceEnum.WECHAT.getSource()).
                            setCreateTime(new Date());
                    thirdPartyUsersService.add(thirdPartyUser);

                    //返回token
                    String jwtToken = JWTUtil.createJWT(String.valueOf(clientUser.getId()), clientUser.getName(), Constants.APP_LOGIN_LIMIT_TIME_SECONDS * 1000L, Constants.JWT_SIGN_KEY);
                    HttpServletResponse response = SpringUtil.getCurrentResponse();
                    response.setHeader(Constants.TOKEN, jwtToken);


                }

            }
        }

        //添加登录记录
        if (Objects.nonNull(clientUser)) {
            ClientUserLoginHistory clientUserLoginHistory = new ClientUserLoginHistory();
            clientUserLoginHistory.setUserId(clientUser.getId());
            clientUserLoginHistory.setLoginTime(new Date());
            clientUserLoginHistoryService.add(clientUserLoginHistory);
        }

        //返回用户信息
        map.put("clientUser", clientUser);


        return Result.success("操作成功", map);
    }

    /**
     * 微信登陆
     *
     * @param params
     * @return
     */
    @Deprecated
    public Result wechatLogin(WechatLoginParams params) {

        //对称解密的目标密文为 Base64_Decode(encryptedData)
        String encryptedData = params.getEncryptedData();
        encryptedData = String.valueOf(Base64.getDecoder().decode(encryptedData));
        //对称解密秘钥 aeskey = Base64_Decode(session_key), aeskey 是16字节
        String sessionKey = params.getSessionKey();
        sessionKey = String.valueOf(Base64.getDecoder().decode(sessionKey));
        //对称解密算法初始向量 为Base64_Decode(iv)
        byte[] iv = Base64.getDecoder().decode(params.getIv());
        //获取解密出的内容
        String encryptedText = AESUtil.decryptWithCBC(encryptedData, sessionKey, iv);
        HashMap map = JSONUtil.strToObj(encryptedText, HashMap.class);
        //获得手机号
        String phoneNumber = (String) map.get("phoneNumber");

        //获取用户信息
        Map userInfo = new WXCommonLoginUtil().userInfo(params.getAccessToken(), params.getOpenId());
        String nickname = (String) userInfo.get("nickname");
        String sex = (String) userInfo.get("sex");
        String province = (String) userInfo.get("province");
        String city = (String) userInfo.get("city");
        String country = (String) userInfo.get("country");
        String headimgurl = (String) userInfo.get("headimgurl");


        //构建信息
        //插入用户信息
        ClientUser clientUser = new ClientUser().setName(nickname).setTelephone(phoneNumber).
                setPassword(MD5EncryptUtil.MD5StringToHexString(Constants.ADMIN_INIT_PASSWORD + Constants.PASSWORD_SALT)).
                setSex(Integer.valueOf(sex)).
                setUserType(1).
                setCreateTime(new Date()).
                setUpdateTime(new Date()).
                setDeleteStatus(BooleanConstant.NO_INTEGER).
                setOpenStatus(BooleanConstant.NO_INTEGER);
        clientUserService.add(clientUser);


        //第三方登陆信息
        ThirdPartyUsers thirdPartyUsers = new ThirdPartyUsers().setOpenid(params.getOpenId()).
                setClientUserId(clientUser.getId()).
                setUsername(nickname).
                setNickname(nickname).
                setAvatar(headimgurl).
                setGender(sex).
                setCreateTime(new Date());
        thirdPartyUsersService.add(thirdPartyUsers);

        //返回token
        String jwtToken = JWTUtil.createJWT(String.valueOf(clientUser.getId()), clientUser.getName(), Constants.APP_LOGIN_LIMIT_TIME_SECONDS * 1000L, Constants.JWT_SIGN_KEY);
        HttpServletResponse response = SpringUtil.getCurrentResponse();
        response.setHeader(Constants.TOKEN, jwtToken);

        return Result.success("登陆成功", clientUser);
    }


    /**
     * 个人认证注册
     *
     * @param params
     * @return
     */
    public Result certificateRegForPerson(CertificateRegForPersonParams params) {

        //判断这个微信用户是否已经注册了
        //如果说这个微信号已经注册了,就直接用这个微信号关联的用户id
        ThirdPartyUsers thirdPartyUsersCondition = new ThirdPartyUsers().setOpenid(params.getOpenId());
        List<ThirdPartyUsers> thirdPartyUsers = thirdPartyUsersService.listByCondition(thirdPartyUsersCondition);

        ClientUser clientUser = null;
        if (Lists.isEmpty(thirdPartyUsers)) {
            //用户之前没有注册过,直接来个人认证
            //创建用户信息
            clientUser = new ClientUser().setName(params.getName()).
                    setTelephone(params.getTelephone()).
                    setPassword(MD5EncryptUtil.MD5StringToHexString(Constants.ADMIN_INIT_PASSWORD + Constants.PASSWORD_SALT)).
                    setSex(0).
                    setUserType(2).
                    setCreateTime(new Date()).
                    setUpdateTime(new Date()).
                    setDeleteStatus(BooleanConstant.NO_INTEGER).
                    setOpenStatus(BooleanConstant.NO_INTEGER);
            clientUserService.add(clientUser);

            //第三方信息
            ThirdPartyUsers thirdPartyUser = new ThirdPartyUsers().setOpenid(params.getOpenId()).
                    setClientUserId(clientUser.getId()).
                    setUsername(params.getName()).
                    setNickname(params.getName()).
                    setAvatar(null).
                    setGender("0").
                    setCreateTime(new Date());
            thirdPartyUsersService.add(thirdPartyUser);
        } else {
            ThirdPartyUsers thirdPartyUser = thirdPartyUsers.get(0);
            Integer clientUserId = thirdPartyUser.getClientUserId();
            ClientAuthenticateSelf clientAuthenticateSelf = clientAuthenticateSelfService.findByUserId(clientUserId);
            if (Objects.nonNull(clientAuthenticateSelf)) {
                //已经注册过了
                return Result.failure("已经认证过了");
            }

            clientUser = clientUserService.findById(clientUserId);
            //用户是普通用户,现在个人认证
        }

        //添加认证信息
        ClientAuthenticateSelf clientAuthenticateSelf = new ClientAuthenticateSelf();
        BeanUtils.copyProperties(params, clientAuthenticateSelf);
        clientAuthenticateSelf.setUserId(clientUser.getId());
        clientAuthenticateSelf.setCreateTime(new Date());
        clientAuthenticateSelf.setUpdateTime(new Date());

        Result result = clientAuthenticateSelfService.add(clientAuthenticateSelf);
        if (!result.getSuccess()) {
            //修改用户状态为个人认证
            clientUser.setUserType(2);
            //修改用户的名字和手机号
            clientUser.setName(params.getName());
            clientUser.setTelephone(params.getTelephone());
            clientUserService.update(clientUser);
        }
        return result;
    }

    /**
     * 商家认证注册
     *
     * @param params
     * @return
     */
    public Result certificateRegForShop(CertificateRegForShopParams params) {
        //判断这个微信用户是否已经注册了
        //如果说这个微信号已经注册了,就直接用这个微信号关联的用户id
        ThirdPartyUsers thirdPartyUsersCondition = new ThirdPartyUsers().setOpenid(params.getOpenId());
        List<ThirdPartyUsers> thirdPartyUsers = thirdPartyUsersService.listByCondition(thirdPartyUsersCondition);

        ClientUser clientUser = null;
        if (Lists.isEmpty(thirdPartyUsers)) {
            //用户之前没有注册过,直接来商家认证
            //创建用户信息
            clientUser = new ClientUser().setName(params.getName()).
                    setTelephone(params.getTelephone()).
                    setPassword(MD5EncryptUtil.MD5StringToHexString(Constants.ADMIN_INIT_PASSWORD + Constants.PASSWORD_SALT)).
                    setSex(0).
                    setUserType(1).//先设置未普通用户,审核通过之后在修改
                    setCreateTime(new Date()).
                    setUpdateTime(new Date()).
                    setDeleteStatus(BooleanConstant.NO_INTEGER).
                    setOpenStatus(BooleanConstant.NO_INTEGER);
            clientUserService.add(clientUser);

            //第三方信息
            ThirdPartyUsers thirdPartyUser = new ThirdPartyUsers().setOpenid(params.getOpenId()).
                    setClientUserId(clientUser.getId()).
                    setUsername(params.getName()).
                    setNickname(params.getName()).
                    setAvatar(null).
                    setGender("0").
                    setCreateTime(new Date());
            thirdPartyUsersService.add(thirdPartyUser);
        } else {
            ThirdPartyUsers thirdPartyUser = thirdPartyUsers.get(0);
            Integer clientUserId = thirdPartyUser.getClientUserId();
            ClientAuthenticateShop clientAuthenticateShop = clientAuthenticateShopService.findByUserId(clientUserId);
            if (Objects.nonNull(clientAuthenticateShop)) {
                //已经注册过了
                return Result.failure("已经认证过了");
            }

            clientUser = clientUserService.findById(clientUserId);
            //用户是普通用户,现在个人认证
        }

        //添加认证信息
        ClientAuthenticateShop clientAuthenticateShop = new ClientAuthenticateShop();
        BeanUtils.copyProperties(params, clientAuthenticateShop);
        clientAuthenticateShop.setUserId(clientUser.getId());
        clientAuthenticateShop.setCreateTime(new Date());
        clientAuthenticateShop.setUpdateTime(new Date());
        //待审核
        clientAuthenticateShop.setReviewStatus(Constants.REVIEW_STATUS_INIT);

        Result result = clientAuthenticateShopService.add(clientAuthenticateShop);
        if (!result.getSuccess()) {
            clientUser.setUserType(3);
            clientUserService.update(clientUser);
        }
        return result;
    }


    /**
     * 后台列表查询小程序用户列表
     *
     * @param params
     * @return
     */
    public Result adminListPage(ClientListQueryParams params) {
        List<ClientUserListVo> list = clientUserService.listPage(params);
        PageInfo<ClientUserListVo> pageInfo = new PageInfo<>(list);
        return Result.success("查询成功", pageInfo);
    }

    /**
     * 主键查询
     *
     * @param id
     * @return
     */
    public Result adminFindById(Integer id) {
        ClientUser clientUser = clientUserService.findById(id);
        if (Objects.isNull(clientUser)) {
            ClientUserSimpleInfoVo vo = new ClientUserSimpleInfoVo();
            vo.setId(clientUser.getId());
            vo.setSex(clientUser.getSex());
            vo.setTelephone(clientUser.getTelephone());
            //查询昵称
            List<ThirdPartyUsers> thirdPartyUsers = thirdPartyUsersService.listByCondition(new ThirdPartyUsers().setClientUserId(id).setSource(UserSourceEnum.WECHAT.getSource()));
            if (Lists.isNotEmpty(thirdPartyUsers)) {
                ThirdPartyUsers thirdPartyUsers1 = thirdPartyUsers.get(0);
                vo.setNickName(thirdPartyUsers1.getNickname());
            }
            return Result.success("查询成功", vo);
        }
        return Result.failure("数据不存在");
    }


    /**
     * 修改小程序用户信息
     *
     * @param params
     * @return
     */
    public Result adminUpdate(AdminUpdateClientUserParams params) {
        //判断用户是否存在
        ClientUser clientUser = clientUserService.findById(params.getId());
        if (Objects.isNull(clientUser)) {
            return Result.failure("数据不存在");
        }

        //密码
        if (StringUtils.isNotEmpty(params.getPassword())) {
            String password = MD5EncryptUtil.MD5StringToHexString(params.getPassword() + Constants.PASSWORD_SALT);
            clientUser.setPassword(password);
        }
        clientUser.setSex(params.getSex());
        clientUser.setTelephone(params.getTelephone());

        Result result = clientUserService.update(clientUser);
        if (result.getSuccess()) {
            //修改第三方信息中的昵称
            List<ThirdPartyUsers> thirdPartyUsers = thirdPartyUsersService.listByCondition(new ThirdPartyUsers().setClientUserId(params.getId()).setSource(UserSourceEnum.WECHAT.getSource()));
            if (Lists.isNotEmpty(thirdPartyUsers)) {
                ThirdPartyUsers thirdPartyUser = thirdPartyUsers.get(0);
                thirdPartyUser.setNickname(params.getNickName());
                thirdPartyUsersService.update(thirdPartyUser);
            }
        }
        return result;
    }

    /**
     * 修改小程序用户为商家会员
     *
     * @param params
     * @return
     */
    public Result adminUpdateClientToShop(AdminUpdateClientUserToShopParams params) {
        //进行修改
        //判断是否已存在,已存在就直接修改,不存在就新增
        ClientAuthenticateShop clientAuthenticateShop = new ClientAuthenticateShop();
        BeanUtils.copyProperties(params, clientAuthenticateShop);
        clientAuthenticateShop.setReviewStatus(1);

        return clientAuthenticateShopService.add(clientAuthenticateShop);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public Result delete(Integer id) {

        //判断是否存在
        ClientUser clientUser = clientUserService.findById(id);
        if (Objects.isNull(clientUser)) {
            return Result.failure("数据不存在");
        }

        clientUser.setDeleteStatus(BooleanConstant.YES_INTEGER);

        Result result = clientUserService.update(clientUser);
        if (result.getSuccess()) {
            //删除第三方信息
            thirdPartyUsersService.deleteByUserId(id);
        }
        return result;
    }

    /**
     * 批量删除
     *
     * @param idList
     * @return
     */
    @Transactional
    public Result batchDelete(List<Integer> idList) {
        if (Lists.isEmpty(idList)) {
            return Result.failure("未选中数据");
        }

        for (Integer id : idList) {
            Result result = delete(id);
            if (!result.getSuccess()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return Result.success("操作成功");
    }

    /**
     * 启用
     *
     * @param id
     * @return
     */
    public Result enable(Integer id) {
        //判断是否存在
        ClientUser clientUser = clientUserService.findById(id);
        if (Objects.isNull(clientUser)) {
            return Result.failure("数据不存在");
        }

        clientUser.setOpenStatus(BooleanConstant.YES_INTEGER);
        return clientUserService.update(clientUser);
    }

    /**
     * 批量启用
     *
     * @param idList
     * @return
     */
    @Transactional
    public Result batchEnable(List<Integer> idList) {
        if (Lists.isEmpty(idList)) {
            return Result.failure("未选中数据");
        }

        for (Integer id : idList) {
            Result result = enable(id);
            if (!result.getSuccess()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return Result.success("操作成功");
    }

    /**
     * 禁用
     *
     * @param id
     * @return
     */
    public Result disable(Integer id) {
        //判断是否存在
        ClientUser clientUser = clientUserService.findById(id);
        if (Objects.isNull(clientUser)) {
            return Result.failure("数据不存在");
        }

        clientUser.setOpenStatus(BooleanConstant.NO_INTEGER);
        return clientUserService.update(clientUser);
    }

    /**
     * 批量禁用
     *
     * @param idList
     * @return
     */
    @Transactional
    public Result batchDisable(List<Integer> idList) {
        if (Lists.isEmpty(idList)) {
            return Result.failure("未选中数据");
        }

        for (Integer id : idList) {
            Result result = disable(id);
            if (!result.getSuccess()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return Result.success("操作成功");
    }


    /**
     * 商家申请列表查询
     *
     * @param params
     * @return
     */
    public Result listPageShopApply(ClientUserShopApplyQueryParams params) {
        List<ShopApplyUserListVo> list = clientAuthenticateShopService.listShopApplyUserListVo(params);
        clientUserService.getFullInfo(list);
        PageInfo<ShopApplyUserListVo> pageInfo = new PageInfo<>(list);
        return Result.success("查询成功", pageInfo);
    }

    /**
     * 同意商家申请
     *
     * @param id
     * @return
     */
    public Result agreeShopApply(Integer id) {
        //查询商家申请是否存在
        ClientAuthenticateShop clientAuthenticateShop = clientAuthenticateShopService.findByUserId(id);
        if (Objects.isNull(clientAuthenticateShop)) {
            return Result.failure("数据不存在");
        }

        clientAuthenticateShop.setReviewStatus(Constants.REVIEW_STATUS_AGGRE);
        Result result = clientAuthenticateShopService.update(clientAuthenticateShop);
        if (!result.getSuccess()) {
            ClientUser clientUser = clientUserService.findById(id);
            if (Objects.nonNull(clientUser)) {
                //认证成功之后修改用户的状态
                clientUser.setUserType(3);
                //修改名字和手机号
                clientUser.setName(clientAuthenticateShop.getName());
                clientUser.setTelephone(clientAuthenticateShop.getTelephone());
                clientUserService.update(clientUser);
            }
        }
        return result;
    }

    /**
     * 批量同意商家申请
     *
     * @return
     */
    @Transactional
    public Result batchAgreeShopApply(List<Integer> idList) {
        if (Lists.isEmpty(idList)) {
            return Result.failure("数据为空");
        }

        for (Integer id : idList) {
            Result result = agreeShopApply(id);
            if (!result.getSuccess()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return Result.success("操作成功");
    }

    /**
     * 拒绝商家申请
     *
     * @return
     */
    public Result denyShopApply(Integer id) {
        //查询商家申请是否存在
        ClientAuthenticateShop clientAuthenticateShop = clientAuthenticateShopService.findByUserId(id);
        if (Objects.isNull(clientAuthenticateShop)) {
            return Result.failure("数据不存在");
        }

        clientAuthenticateShop.setReviewStatus(Constants.REVIEW_STATUS_DENY);
        return clientAuthenticateShopService.update(clientAuthenticateShop);
    }

    /**
     * 批量拒绝商家申请
     *
     * @return
     */
    @Transactional
    public Result batchDenyShopApply(List<Integer> idList) {
        if (Lists.isEmpty(idList)) {
            return Result.failure("数据为空");
        }

        for (Integer id : idList) {
            Result result = denyShopApply(id);
            if (!result.getSuccess()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return Result.success("操作成功");
    }

    /**
     * 查询商家申请详情
     *
     * @return
     */
    public Result findShopApplyInfo(Integer id) {
        ClientAuthenticateShop clientAuthenticateShop = clientAuthenticateShopService.findByUserId(id);
        return Result.success("查询成功", clientAuthenticateShop);
    }

}
